package com.wang.example.netty.codec.fixed;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;

import java.io.IOException;


public class FixedEchoServer {
    private int port;
    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;
    private ServerBootstrap b;

    public FixedEchoServer(int port) {
        this.port = port;
        //第一个线程组是用于接收Client连接的
        bossGroup = new NioEventLoopGroup(1);
        //第二个线程组是用于消息的读写操作
        workGroup = new NioEventLoopGroup(2);
        //服务端辅助启动类
        b = new ServerBootstrap();
        b.group(bossGroup, workGroup)
                //需要指定使用NioServerSocketChannel这种类型的通道
                .channel(NioServerSocketChannel.class)
                //向ChannelPipeline里添加业务处理handler
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast( new FixedLengthFrameDecoder(100));
                        ch.pipeline().addLast(new FixedServerInHandler());
                    }
                });
    }

    /**
     * 启动
     * @throws InterruptedException
     */
    public void start() throws InterruptedException {
        try {
            //绑定到端口，阻塞等待直到完成
            b.bind(this.port).sync();
            System.out.println("服务器启动成功");
        } finally {

        }
    }

    /**
     * 资源优雅释放
     */
    public void close() {
        try {
            if (bossGroup != null)
            bossGroup.shutdownGracefully().sync();
            if (workGroup != null)
            workGroup.shutdownGracefully().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException, IOException {
        int port = 9999;
        FixedEchoServer echoServer = new FixedEchoServer(port);
        try {
            echoServer.start();
            //防止主程序退出
            System.in.read();
        } finally {
            echoServer.close();
        }

    }
}
